// pages/content/maxpay.js
var app = getApp();
var rsa = require('../../utils/rsa.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    items: [
      { name: 'cash', value: '现金' },
      { name: 'wx', value: '扫码付', checked: 'true' }
    ],
    array: [],
    index: 0,
    payamount: '',  //消费金额
    couponcode:'',
    order_id:'', //订单号
    spayamount:'',  //实收金额
    dkmoney:'', //抵扣金额
    symoney:'',//剩余金额
    payType:'wx', // 支付方式
    ylviewshow:false,
    payimage:'',  //云闪付图片
    paytext:'', //云闪付结果
    payment_id:'', //支付单号
    menmbrid:'', //会员卡号

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const order = options.ordeid;
    const vip = options.vip;
    if (vip != "undefined"){
      this.queryvip(vip);
    }
    this.checkorder(order);
    // this.querShopcounpon();
  },
  //vip数据查询
  queryvip:function(e){
    console.log('vip'+e);
    var shopnum = app.globalData.shoopnum;
    const setion = app.globalData.session;
    wx.showLoading({
      title: '请求中...',
      mask: true,
    })
    rsa.Cpic_fetchPost(rsa.SERVERPORT, {
      'method': 'promotion.member_regist', "seller_bn": shopnum, "session_id": setion, "mobile": e
    }, (err, res) => {
      wx.hideLoading();
      if (err) {
        return;
      }
      var itemp = this.data.items;
      const subitm = { name: 'hyk', value: '会员卡' };
      itemp.push(subitm);
      this.setData({
        array: res.data.coupon_list, //vip详情
        items:itemp,
        menmbrid: res.data.member_id, //会员卡号
        
      })
    })


  },
  //收款完成
  finishPay:function(){
    wx.navigateBack({
      delta: 2
    })
  },

  //确认收款
  payAction:function(){
    const payt = this.data.payType;
    switch (payt){
      case 'cash':
        this.cashpay();
      break;

      case 'wx':
        wx.scanCode({
          success: (res) => {
            var vele = res.result;
            this.scanpay(vele);
          }
        })
      break;
      case 'pal':
        wx.scanCode({
          success: (res) => {
            var vele = res.result;
            this.scanpay(vele);
          }
        })
      break;
      case 'yl':
        this.yunSacn();
      break;
      case 'hyk':
        this.huiyuanPay();
      break;
    }
  },
  //会员卡支付
  huiyuanPay:function(){
    const memberid = this.data.menmbrid;
    if (memberid == ''){
      return;
    }
    const shopnum = app.globalData.shoopnum;
    const settion = app.globalData.session;
    const payvalue = this.data.symoney;
    var paymont = (parseFloat(payvalue) * 100).toFixed(0);
    if (paymont <= 0) {
      wx.showModal({
        title: '提示',
        content: '实收金额为0，不能收款',
        showCancel: false,
        success: function (res) {
        }
      })
      return;
    }
    const orid = this.data.order_id
    wx.showLoading({
      title: '数据交互中...',
      mask: true,
    })
    rsa.Cpic_fetchPost(rsa.SERVERPORT, {
      'method': 'orders.pay_advance', "seller_bn": shopnum, 'session_id': settion, 'order_id': orid, 'pay_amount': paymont, 'member_id': memberid }, (err, res) => {
      wx.hideLoading()
      wx.hideLoading()
      if (err != '') {
        wx.showModal({
          title: '提示',
          content: err,
          showCancel: false,
          success: function (res) {
          }
        })
        return
      }
      var res_data = res.data;
      if (!res_data) {
        wx.showToast({
          title: res.return_msg,
          icon: 'none',
          duration: 5000
        })
        return;
      }
      var paystatus = res_data.pay_status;
      // 付款状态（0：未支付，1：已支付，3：部分付款，4：部分退款，5：全额退款）
      var temstr = '' //标题
      var notice = '' // 提示
      const repay = res_data.still_amount; //待支付金额
      const paym = payvalue;
      switch (paystatus) {
        case '0':
          temstr = '收款失败';
          notice = '请重新收款';
          break;
        case '1':
          temstr = '收款完成';
          notice = "已收金额：" + paym + "，返回上个界面";
          break;
        case '3':
          temstr = '部分付款';
          notice = "已收金额：" + paym + ',待收金额：' + repay + '，请继续收款';
          break;
        case '4':
          temstr = '部分退款';
          notice = "已退金额：" + paym;
          break;
        case '5':
          temstr = '全额退款';
          notice = "已退金额：" + paym;
          break;
      }
      this.setData({
        spayamount: repay,
        dkmoney: '0', //抵扣金额
        symoney: repay,//剩余金额
      })
      wx.showModal({
        title: temstr,
        content: notice,
        showCancel: false,
        success: function (res) {
          if (temstr == "收款完成") {
            wx.navigateBack({
              delta: 2
            })
          }
        }
      })
      })

  },
  //云闪付主扫
  yunSacn:function(){
    const shopnum = app.globalData.shoopnum;
    const settion = app.globalData.session;
    const payvalue = this.data.symoney;
    var paymont = (parseFloat(payvalue) * 100).toFixed(0);
    if (paymont <= 0) {
      wx.showModal({
        title: '提示',
        content: '实收金额为0，不能收款',
        showCancel: false,
        success: function (res) {
        }
      })
      return;
    }
    const orid = this.data.order_id
    wx.showLoading({
      title: '数据交互中...',
      mask: true,
    })
    rsa.Cpic_fetchPost(rsa.SERVERPORT, { 'method': 'orders.pay_scan', "seller_bn": shopnum, 'session_id': settion, 'order_id': orid, 'pay_amount': paymont, 'pay_type': "unionpay" }, (err, res) => {
      wx.hideLoading()
      if (err != '') {
        wx.showModal({
          title: '提示',
          content: err,
          showCancel: false,
          success: function (res) {
          }
        })
        return
      }
      var res_data = res.data;
      this.setData({
        payimage: res_data.qrcode_url,
        payment_id: res_data.payment_id,
        paytext:'交易中，点击刷新查询交易结果',
        ylviewshow: true,
      })
    });
  },
  //云闪付刷新
  yunsfleshAction:function(){
    const shopnum = app.globalData.shoopnum;
    const settion = app.globalData.session;
    const payid = this.data.payment_id;
 
    wx.showLoading({
      title: '数据交互中...',
      mask: true,
    })
    rsa.Cpic_fetchPost(rsa.SERVERPORT, { 'method': 'payment.payquery', "seller_bn": shopnum, 'session_id': settion, 'payment_id': payid}, (err, res) => {
      wx.hideLoading()
      if (err != '') {
        wx.showModal({
          title: '提示',
          content: err,
          showCancel: false,
          success: function (res) {
          }
        })
        return
      }
      var res_data = res.data;
      var pay_status = res_data.status;
      var pay_title = '';
      if (pay_status == "succ"){
         pay_title = '支付成功';
      }else{
         pay_title = '支付中';
      }
      var payed = res_data.pay_status;
      
      this.setData({
        paytext:pay_title,
      })
    });


  },
  //微信支付宝被扫·
  scanpay: function (e) {
    const shopnum = app.globalData.shoopnum;
    const settion = app.globalData.session;
    const payvalue = this.data.symoney;
    var paymont = (parseFloat(payvalue) * 100).toFixed(0);
    if (paymont <= 0) {
      wx.showModal({
        title: '提示',
        content: '实收金额为0，不能收款',
        showCancel: false,
        success: function (res) {
        }
      })
      return;
    }
    const orid = this.data.order_id
    wx.showLoading({
      title: '数据交互中...',
      mask:true,
    })
    rsa.Cpic_fetchPost(rsa.SERVERPORT, { 'method': 'orders.micropay', "seller_bn": shopnum, 'session_id': settion, 'order_id': orid, 'pay_amount': paymont,'auth_code':e}, (err, res) => {
      wx.hideLoading()
      if (err != '') {
        wx.showModal({
          title: '提示',
          content: err,
          showCancel:false,
          success: function (res) {
          }
        })
        return
      }
      var res_data = res.data;
     
      var paystatus = res_data.pay_status;
      // 付款状态（0：未支付，1：已支付，3：部分付款，4：部分退款，5：全额退款）
      var temstr = '' //标题
      var notice = '' // 提示
      const repay = res_data.still_amount; //待支付金额
      const paym = payvalue;
      switch (paystatus) {
        case '0':
          temstr = '收款失败';
          notice = '请重新收款';
          break;
        case '1':
          temstr = '收款完成';
          notice = "已收金额：" + paym + "，返回上个界面";
          break;
        case '3':
          temstr = '部分付款';
          notice = "已收金额：" + paym + ',待收金额：' + repay + '，请继续收款';
          break;
        case '4':
          temstr = '部分退款';
          notice = "已退金额：" + paym;
          break;
        case '5':
          temstr = '全额退款';
          notice = "已退金额：" + paym;
          break;
      }
      this.setData({
        spayamount: repay,
        dkmoney: '0', //抵扣金额
        symoney: repay,//剩余金额
      })
      wx.showModal({
        title: temstr,
        content: notice,
        showCancel: false,
        success: function (res) {
        }
      })
    });

  },
  //现金支付
  cashpay:function(){
    const shopnum = app.globalData.shoopnum;
    const settion = app.globalData.session;
    const payvalue = this.data.symoney;
    var paymont = (parseFloat(payvalue)*100).toFixed(0);
    if (paymont<=0){
      wx.showModal({
        title: '提示',
        content: '实收金额为0，不能收款',
        showCancel: false,
        success: function (res) {
        }
      })
      return;
    }
    const orid = this.data.order_id
    wx.showLoading({
      title: '数据交互中...',
      mask: true,
    })
    rsa.Cpic_fetchPost(rsa.SERVERPORT, { 'method': 'orders.pay_cash', "seller_bn": shopnum, 'session_id': settion, 'order_id': orid, 'pay_amount': paymont}, (err, res) => {
      wx.hideLoading()
      if (err != '') {
        wx.showModal({
          title: '提示',
          content: err,
          showCancel: false,
          success: function (res) {
          }
        })
        return
      }
      var res_data = res.data;
      if (!res_data) {
        wx.showToast({
          title: res.return_msg,
          icon: 'none',
          duration: 5000
        })
        return;
      }
      var paystatus = res_data.pay_status;
      // 付款状态（0：未支付，1：已支付，3：部分付款，4：部分退款，5：全额退款）
      var temstr = '' //标题
      var notice='' // 提示
      const repay = res_data.still_amount; //待支付金额
      const paym = payvalue;
      switch (paystatus){
        case '0':
        temstr = '收款失败';
        notice = '请重新收款';
        break;
        case '1':
          temstr = '收款完成';
          notice = "已收金额：" + paym+"，返回上个界面";
        break;
        case '3':
          temstr = '部分付款';
          notice = "已收金额：" + paym +',待收金额：'+repay+'，请继续收款';
        break;
        case '4':
          temstr = '部分退款';
          notice = "已退金额：" + paym;
        break;
        case '5':
          temstr = '全额退款';
          notice = "已退金额：" + paym;
        break;
      }
      this.setData({
        spayamount: repay,
        dkmoney: '0', //抵扣金额
        symoney: repay,//剩余金额
      })
      wx.showModal({
        title: temstr,
        content: notice,
        showCancel: false,
        success: function (res) {
          if(temstr =="收款完成"){
            wx.navigateBack({
              delta: 2
            })
          }
        }
      })
    });
  },
  //银联收款关闭
  hiddylAction:function(){
    this.setData({
      ylviewshow:false,
    })
  },
  
  //查询门店参加的券活动
  querShopcounpon: function () {
    const shopnum = app.globalData.shoopnum;
    const settion = app.globalData.session;
    rsa.Cpic_fetchPost(rsa.SERVERPORT, { 'method': 'store.coupons', "seller_bn": shopnum, 'session_id': settion}, (err, res) => {
      if (!res || res == '') {
        wx.showToast({
          title: err,
          icon: 'none',
          duration: 5000
        })
        return
      }
      var res_data = res.data;
      if (!res_data) {
        wx.showToast({
          title: res.return_msg,
          icon: 'none',
          duration: 5000
        })
        return;
      }
      var rstatus = res_data.list;//券列表
      if (rstatus.length > 0) {
        this.setData({
          array: rstatus,
        })
      }else {
        wx.showToast({
          title: '无券',
          icon: 'loading',
          duration: 5000
        })
      }
    });
  },
  //查询订单
  checkorder: function (e) {
    const shopnum = app.globalData.shoopnum;
    const settion = app.globalData.session;
    wx.showLoading({
      title: '加载中',
      mask:true,
    })

    rsa.Cpic_fetchPost(rsa.SERVERPORT, {
      'method': 'orders.query', "seller_bn": shopnum, 'session_id': settion, "order_id": e
    }, (err, res) => {
      wx.hideLoading();

      if (!res || res == '') {
        wx.showToast({
          title: err,
          icon: 'none',
          duration: 5000
        })
        return
      }
      var res_data = res.data;
      if (!res_data) {
        wx.showToast({
          title: res.return_msg,
          icon: 'none',
          duration: 5000
        })
        return;
      }
      var status = res_data.pay_status; //支付状态（0：未付款，1：已付款）
      if (status == '0') {
        var moey = res_data.total_amount;
        this.setData({
          payamount: moey,
          order_id: res_data.order_id,
          spayamount:moey,
          dkmoney: '0', //抵扣金额
          symoney: moey, //剩余金额
        })

      } else if (status == '1') {
        wx.showModal({
          title: '提示',
          content: '已支付',
          showCancel: false,
          success: function (res) {
          }
        })
      } else {
        wx.showToast({
          title: status,
          icon: 'loading',
          duration: 5000
        })
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  bindPickerChange:function(e){
    const vl = e.detail.value;
    this.setData({
      index:vl,
    })
    const hex = this.data.array;
    var qcode = hex[vl].qrcode;
    this.deCoupon(qcode);
    this.setData({
      couponcode: qcode,
    })
  },
  xifaction:function(e){
    var value = e.detail.value;
    this.setData({
      payamount:value,
      spayamount:value,
      dkmoney: '0', //抵扣金额
      symoney: value, //剩余金额
    })
  },
  shaction:function(e){
    var value = e.detail.value;
    this.setData({
      spayamount: value,
      dkmoney: '0', //抵扣金额
      symoney: value, //剩余金额
    })
  },
  //扫描券
  scanCouponAction: function () {
    var that =this;
    wx.scanCode({
      success: (res) => {
        var vele = res.result;
        that.deCoupon(vele);
        that.setData({
          couponcode:vele,
        })
      }
    })
  },
  //使用
  couponuse:function(e){
    const vle = e.detail.value;
    this.deCoupon(vle);
  },
  //收款方式
  radioChange:function(e){
    this.setData({
      payType:e.detail.value,
    })
  },
  //核销券
  deCoupon:function(e){
    const shopnum = app.globalData.shoopnum;
    const settion = app.globalData.session;
    const oderid = this.data.order_id;
    const vlue = this.data.spayamount;
    var tmoney = (parseFloat(vlue)*100).toFixed(0);
    if (tmoney <= 0) {
      wx.showModal({
        title: '提示',
        content: '实收金额为0，不能核销券',
        showCancel: false,
        success: function (res) {
        }
      })
      return;
    }
    rsa.Cpic_fetchPost(rsa.SERVERPORT, {
      'method': 'coupon.deduction', "seller_bn": shopnum, 'session_id': settion, 'order_id': oderid, 'code': e, 'total_money': tmoney}, (err, res) => {
      if (!res || res == '') {
        wx.showModal({
          title: '提示',
          content: err,
          showCancel: false,
          success: function (res) {
          }
        })
        this.setData({
          dkmoney: '0',
          symoney: vlue,
        })

        return
      }
      if (res.return_code !='0000'){
        this.setData({
          dkmoney: '0',
          symoney: vlue,
        })
        wx.showToast({
          title: '优惠券不存在',
          icon:'none',
          duration:2000
        })
        return;
      }
      var res_data = res.data;
      if (!res_data) {
        wx.showToast({
          title: res.return_msg,
          icon: 'none',
          duration: 5000
        })
        return;
      }
      var rstm = res_data.off_amount;  //抵扣金额
      var rman = res_data.remain_amount; //抵扣剩余
      this.setData({
        dkmoney: rstm,
        symoney:rman,
        spayamount: rman,
      })

    });
  }
})